﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using AutoMapper.Internal.Mappers;
using BW.WMS.BasicData_LC.Dto.Input;
using BW.WMS.BasicData_LC.Dto.OutPut;
using BW.WMS.CodeEnum;
using BW.WMS.LC.Dto.Input;
using BW.WMS.LC.Dto.OutPut;
using BW.WMS.Model;
using Microsoft.Extensions.Logging;
using NPOI.XSSF.UserModel;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;

namespace BW.WMS.LC
{
    public class WareHouserAppService : ApplicationService, IWareHouserAppService
    {
        private readonly IRepository<Dm_Warehouser, Guid> _repository;
        private readonly IRepository<Dm_Dep, Guid> depRepository;
        private readonly IRepository<Dm_Librarylocation, Guid> librarylocationRepository;

        public WareHouserAppService(IRepository<Dm_Warehouser, Guid> repository, 
            IRepository<Dm_Dep, Guid> depRepository,
            IRepository<Dm_Librarylocation, Guid> librarylocationRepository)
        {
            _repository = repository;
            this.depRepository = depRepository;
            this.librarylocationRepository = librarylocationRepository;
        }



        /// <summary>
        /// 添加部门
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>

        public async Task<ApiResult<int>> AddDep(AddDepInput input)
        {
            input.Id=Guid.NewGuid();
            var result = new ApiResult<int>();
            result.Code = ApiEnum.Success;
            result.Message = "创建成功";
            var book = ObjectMapper.Map<AddDepInput, Dm_Dep>(input);
            book.Updepid = "";
            book.Depnum = 0;
            var a = await depRepository.InsertAsync(book);

            result.Data = 1;

            if (a == null)
            {
                result.Code = ApiEnum.Error;
                result.Message = "创建失败";
                result.Data = -1;
            }
            return result;
        }


        /// <summary>
        /// 创建仓库
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> CreateWareHouser(CreateUpdateWareHouserDtoInput input)
        {
            var result=new ApiResult<int>();
            result.Code = ApiEnum.Success;
            result.Message = "创建成功";
            var book = ObjectMapper.Map<CreateUpdateWareHouserDtoInput, Dm_Warehouser>(input);
          
          var a=  await _repository.InsertAsync(book);

            result.Data = 1;

            if (a == null)
            {
                result.Code = ApiEnum.Error;
                result.Message = "创建失败";
                result.Data = -1;
            }
            return result;

        }
        /// <summary>
        /// 删除仓库
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> DeleteWareHouser(Guid id)
        {
            var result = new ApiResult<int>();
            result.Code = ApiEnum.Success;
            result.Message = "删除成功";


            var list=await _repository.GetAsync(id);
            
           await   _repository.DeleteAsync(list);

            result.Data = 1;

            if (list == null)
            {
                result.Code = ApiEnum.Error;
                result.Message = "删除失败";
                result.Data = -1;
            }

            return result;
        }

        ///导出

        public async Task<ApiResult<byte[]>> ExportWareHouserDataAsync(WareHouserDtoOutPut outPut)
        {
            var result = new ApiResult<byte[]>();

            var query = await _repository.GetQueryableAsync();

            // 获取所有数据
            var list = query.OrderBy(a => a.CreationTime).ToList();
            var dtos = ObjectMapper.Map<List<Dm_Warehouser>, List<WareHouseDto>>(list);

            // 创建Excel工作簿
            var workbook = new XSSFWorkbook();
            var sheet = workbook.CreateSheet("仓库数据");

            // 创建标题行
            var headerRow = sheet.CreateRow(0);
            headerRow.CreateCell(0).SetCellValue("仓库编码");
            headerRow.CreateCell(1).SetCellValue("仓库名称");
            headerRow.CreateCell(2).SetCellValue("仓库容量");
            headerRow.CreateCell(3).SetCellValue("地址");
            headerRow.CreateCell(4).SetCellValue("部门名称");
            headerRow.CreateCell(5).SetCellValue("库位数量");
            headerRow.CreateCell(6).SetCellValue("状态");
            headerRow.CreateCell(7).SetCellValue("创建时间");

            for (int i = 0; i < dtos.Count; i++)
            {
                var row = sheet.CreateRow(i + 1);
                row.CreateCell(0).SetCellValue(dtos[i].Warehouseid);
                row.CreateCell(1).SetCellValue(dtos[i].Warehousename);
                row.CreateCell(2).SetCellValue(dtos[i].Capacity);
                row.CreateCell(3).SetCellValue(dtos[i].Address);
                row.CreateCell(4).SetCellValue(dtos[i].Depid);
                row.CreateCell(5).SetCellValue(dtos[i].Librarylocationnum);

                // 状态: 0=启用, 1=停用, 2=锁定
                string status = dtos[i].Status == 0 ? "启用" :
                               (dtos[i].Status == 1 ? "停用" : "锁定");
                row.CreateCell(6).SetCellValue(status);

                row.CreateCell(7).SetCellValue(dtos[i].CreationTime.ToString("yyyy-MM-dd HH:mm:ss"));
            }

            for (int i = 0; i < 8; i++)
            {
                sheet.AutoSizeColumn(i);
            }

            using (var ms = new MemoryStream())
            {
                workbook.Write(ms);

                result.Data = ms.ToArray();
                result.Code = ApiEnum.Success;
                result.Message = "导出成功";
            }

            return result;

        }

        /// <summary>
        /// 获取部门列表
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<List<DepartmentDto>>> GetDepartmentList()
        {
            var result = new ApiResult<List<DepartmentDto>>();

            try
            {
                var departmentsQuery = await depRepository.GetQueryableAsync();

                var departmentsList = departmentsQuery.ToList();

                var dtos = ObjectMapper.Map<List<Dm_Dep>, List<DepartmentDto>>(departmentsList);

                return new ApiResult<List<DepartmentDto>> 
                {
                    Code = ApiEnum.Success,
                    Message = "获取部门列表成功",
                    Data = dtos
                };
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "获取部门列表时出错");
                result.Code = ApiEnum.Error;
                result.Message = $"获取部门列表出错: {ex.Message}";
            }

            return result;
        }


        /// <summary>
        /// 展示所有仓库+查询+分页8
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ApiPaging<WareHouseDto>> GetWareHouserList(WareHouserDtoOutPut input)
        {
            var query = await _repository.GetQueryableAsync();
            if (!string.IsNullOrWhiteSpace(input.WareHouseName))
            {
                query = query.Where(a => a.Warehousename.Contains(input.WareHouseName));
            }


            if (!string.IsNullOrWhiteSpace(input.Warehouseid))
            {
                query = query.Where(b => b.Warehouseid == input.Warehouseid);
            }


            var totalcount = query.Count();

            var list = query.OrderByDescending(a => a.CreationTime).Skip((input.pageindex - 1) * input.pagesize).Take(input.pagesize).ToList();


            var result = new ApiPaging<WareHouseDto>
            {
                Code = ApiEnum.Success,
                Message = "查询成功",
                TotalCount = totalcount,
                TotalPages = (int)Math.Ceiling(totalcount / (double)input.pagesize),
                PageData = ObjectMapper.Map<List<Dm_Warehouser>, List<WareHouseDto>>(list)
            };

            return result;
        }
        /// <summary>
        /// 更新仓库
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> UpdateWareHouser(CreateUpdateWareHouserDtoInput input)
        {
            var result = new ApiResult<int>();
            
            try
            {
                // 1. 先检查仓库是否存在
                var existingWarehouser = await _repository.GetAsync(input.Id);
                if (existingWarehouser == null)
                {
                    result.Code = ApiEnum.Error;
                    result.Message = "更新失败：找不到指定的仓库";
                    result.Data = -1;
                    return result;
                }
                
                // 2. 使用对象映射器更新实体属性，保留现有数据
                ObjectMapper.Map(input, existingWarehouser);

                // 3. 更新实体
                input.CreationTime = DateTime.Now;
                existingWarehouser.CreationTime = DateTime.Now;
                var updatedWarehouser = await _repository.UpdateAsync(existingWarehouser);
                
                result.Code = ApiEnum.Success;
                result.Message = "更新成功";
                result.Data = 1;
                
                return result;
            }
            catch (Exception ex)
            {
                // 4. 完善错误处理
                Logger.LogError(ex, "更新仓库时出错，仓库ID: {WarehoyserId}", input.Id);
                result.Code = ApiEnum.Error;
                result.Message = $"更新失败: {ex.Message}";
                result.Data = -1;
                return result;
            }
        }
            
        
    }
}
